package com.ruicar.afs.cloud.apply.admin.manage.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.apply.admin.auth.util.DataAccessUtil;
import com.ruicar.afs.cloud.apply.admin.manage.entity.*;
import com.ruicar.afs.cloud.apply.admin.manage.mapper.ApplyDepartmentMapper;
import com.ruicar.afs.cloud.apply.admin.manage.service.*;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.modules.apply.enums.CarTypeEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.LockFlagEnum;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date 2020-06-01 06:10:56
 * @description
 */
@AllArgsConstructor
@Service
public class ApplyDepartmentServiceImpl extends ServiceImpl<ApplyDepartmentMapper, SysDepartment> implements ApplyDepartmentService {

    private final ApplyDeptAuthRegionService sysDeptAuthRegionService;
    private final ApplyUserService applyUserService;
    private final ApplyChannelAuthRegionService orgAuthorizeRegionService;
    private final ApplyChannelBasicInfoService applyChannelBasicInfoService;
    private final ApplyUserTempService applyUserTempService;


    @Override
    public List<SysDepartment> channelSearch(String title, Long channelId) {
        return baseMapper.selectList(Wrappers.<SysDepartment>query().lambda()
                .like(SysDepartment::getTitle, title).orderByAsc(SysDepartment::getSortOrder).eq(SysDepartment::getChannelId, channelId));
    }

    @Override
    public List<SysDepartment> findByTitle(String title) {
        return baseMapper.selectList(Wrappers.<SysDepartment>query().lambda()
                .like(SysDepartment::getTitle, title).orderByAsc(SysDepartment::getSortOrder));
    }

    @Override
    public void deleteByIds(Long[] ids) {
        ArrayList<Long> idsArr = Lists.newArrayList();
        for (Long id : ids) {
            idsArr.add(id);
            this.getDepartmentIds(idsArr, id);
        }
        List<Long> list = idsArr.stream().distinct().collect(Collectors.toList());
        List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query()
                .lambda().in(SysUser::getDeptId, list));
        if (ObjectUtils.isNotEmpty(users)) {
            throw new AfsBaseException(CommonConstants.FAIL, "部门下存在用户不允许删除");
        }
        // TODO Lee 需要进件接口根据部门id查询订单
        // 判断这个部门下面有没有人  如果有人就不可以删除
        List<SysUser> userList =applyUserService.list(Wrappers.<SysUser>query().lambda().in(SysUser::getDeptId,ids));
        if(userList.size()>0){
            throw new AfsBaseException("部门下有用户请先调换部门！");
        }
        List<SysUserTemp> userTempList =applyUserTempService.list(Wrappers.<SysUserTemp>query().lambda().in(SysUserTemp::getDeptId,ids));
        if(userTempList.size()>0){
            throw new AfsBaseException("部门下有用户请先调换部门！");
        }
        //删除部门表数据
        removeByIds(idsArr);
        //删除授权区域表
        sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                .lambda().in(SysDeptAuthRegion::getDeptId, ids));
    }

    @Override
    public void deleteById(Long id) {
        // 先查询父类信息
        SysDepartment ss = this.baseMapper.selectById(id);
        SysDepartment pp = this.baseMapper.selectById(ss.getParentId());
        // 根据id 查询 他自己这一集和下级的id
        ArrayList<Long> idsArr = Lists.newArrayList();
        idsArr.add(id);
        this.getDepartmentIds(idsArr, id);

        List<Long> list = idsArr.stream().distinct().collect(Collectors.toList());
        List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query()
                .lambda().in(SysUser::getDeptId, list));
        if (ObjectUtils.isNotEmpty(users)) {
            throw new AfsBaseException(CommonConstants.FAIL, "部门下存在用户不允许删除");
        }
        // TODO Lee 需要进件接口根据部门id查询订单
        //删除部门表数据
        removeByIds(idsArr);
        //删除授权区域表
        sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                .lambda().in(SysDeptAuthRegion::getDeptId, list));
        // 查下删除后的父级还有没有下级
        List<SysDepartment> queryList = this.baseMapper.selectList(Wrappers.<SysDepartment>lambdaQuery().eq(SysDepartment::getParentId, pp.getId()));
        if (queryList.size() == 0) {
            pp.setIsParent(Boolean.FALSE);
            this.baseMapper.updateById(pp);
        }


    }


    @Override
    public List<SysDepartment> findAllSubByParentId(Long parentId) {
        List<SysDepartment> queryList = this.baseMapper.selectList(Wrappers.<SysDepartment>lambdaQuery().eq(SysDepartment::getParentId, parentId));
        if (queryList.size() == 0) {
            return queryList;
        }
        List<SysDepartment> rtnList = new ArrayList<>();
        queryList.forEach(dept -> {
            rtnList.add(dept);
            rtnList.addAll(findAllSubByParentId(dept.getId()));
        });
        return rtnList;
    }

    @Override
    public void saveDepartment(SysDepartment department) {
        Long ffId = department.getParentId();
        department.setChannelId(DataAccessUtil.getChannelId());
        ArrayList<SysDepartment> list = Lists.newArrayList();
        this.getDepartmentUp(list, department.getParentId());
        //控制非管理员数据权限
        if (DataAccessUtil.isAdmin()) {
            SysChannelBasicInfo one = applyChannelBasicInfoService.getOne(Wrappers.<SysChannelBasicInfo>lambdaQuery().eq(SysChannelBasicInfo::getChannelId, DataAccessUtil.getChannelId()));
            Integer hierarchy = one.getHierarchy();
            if (list.size() + 1 > hierarchy) {
                throw new AfsBaseException(CommonConstants.FAIL, "部门创建超过最大层级");
            }
        }

        if (department.getId() == null) {
            save(department);
            SysDepartment byId = getById(department.getParentId());
            if (byId != null) {
                byId.setIsParent(Boolean.TRUE);
                updateById(byId);
            }
        } else {
            updateById(department);
        }

        sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getDeptId, department.getId()));

        //新车展业区域
        ArrayList<SysDeptAuthRegion> newCarIds = Lists.newArrayList();
        if(department.getNewCarRegion().size()>0){
            if("0".equals(department.getNewCarRegion().get(0).getParentId().toString())&&department.getNewCarRegion().get(0).getChecked()){
                // 说明点击的是全国那么直接把上级所有的都给他
                List<SysDeptAuthRegion> pRegion =sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,department.getNewCarRegion().get(0).getDeptId()).eq(SysDeptAuthRegion::getBusinessType,department.getNewCarRegion().get(0).getBusinessType()));
                if(pRegion.size()>0){
                    for (SysDeptAuthRegion region :pRegion){
                        region.setDeptId(department.getId());
                        newCarIds.add(region);
                    }
                }
            }else {
                for (SysDeptAuthRegion deptAuthRegion : department.getNewCarRegion()) {
                    deptAuthRegion.setDeptId(department.getId());
                    deptAuthRegion.setBusinessType(CarTypeEnum.newCar);
                    deptAuthRegion.setIsChecked(deptAuthRegion.getChecked());
                    deptAuthRegion.setChannelId(DataAccessUtil.getChannelId());
                    newCarIds.add(deptAuthRegion);
                    if (deptAuthRegion.getChecked()) {
                        this.getRegionIds(newCarIds, deptAuthRegion.getCode(), department.getId(), DataAccessUtil.getChannelId(), CarTypeEnum.newCar,department.getParentId());
                    }
                }
                if (newCarIds.size() > 0) {
                    SysDeptAuthRegion gg = new SysDeptAuthRegion();
                    gg.setCode("1");
                    gg.setParentId("0");
                    gg.setTitle("全国区域");
                    gg.setIsParent(true);
                    gg.setDeptId(department.getId());
                    gg.setBusinessType(CarTypeEnum.newCar);
                    gg.setIsChecked(true);
                    gg.setChannelId(DataAccessUtil.getChannelId());
                    newCarIds.add(gg);
                }
            }
        }



        List<SysDeptAuthRegion> newCarRegionIds = newCarIds.stream().collect(Collectors.toMap
                (SysDeptAuthRegion::getCode, Function.identity(), (en1, en2) -> en2)).values().stream().collect(Collectors.toList());

        //二手车展业区域
        ArrayList<SysDeptAuthRegion> oldCarIds = Lists.newArrayList();
        if(department.getOldCarRegion().size()>0){
            if("0".equals(department.getOldCarRegion().get(0).getParentId().toString())&&department.getOldCarRegion().get(0).getChecked()){
                // 说明点击的是全国那么直接把上级所有的都给他
                List<SysDeptAuthRegion> pRegion =sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,department.getOldCarRegion().get(0).getDeptId()).eq(SysDeptAuthRegion::getBusinessType,department.getOldCarRegion().get(0).getBusinessType()));
                if(pRegion.size()>0){
                    for (SysDeptAuthRegion region :pRegion){
                        region.setDeptId(department.getId());
                        oldCarIds.add(region);
                    }
                }
            }else {
                for (SysDeptAuthRegion deptAuthRegion : department.getOldCarRegion()) {
                    deptAuthRegion.setDeptId(department.getId());
                    deptAuthRegion.setBusinessType(CarTypeEnum.oldCar);
                    deptAuthRegion.setIsChecked(deptAuthRegion.getChecked());
                    deptAuthRegion.setChannelId(DataAccessUtil.getChannelId());
                    oldCarIds.add(deptAuthRegion);
                    if (deptAuthRegion.getChecked()) {
                        this.getRegionIds(oldCarIds, deptAuthRegion.getCode(), department.getId(), DataAccessUtil.getChannelId(), CarTypeEnum.oldCar,department.getParentId());
                    }
                }
                if (oldCarIds.size() > 0) {
                    SysDeptAuthRegion ff = new SysDeptAuthRegion();
                    ff.setCode("1");
                    ff.setParentId("0");
                    ff.setTitle("全国区域");
                    ff.setIsParent(true);
                    ff.setDeptId(department.getId());
                    ff.setBusinessType(CarTypeEnum.oldCar);
                    ff.setIsChecked(true);
                    ff.setChannelId(DataAccessUtil.getChannelId());
                    oldCarIds.add(ff);
                }
            }
        }

        List<SysDeptAuthRegion> oldCarRegionIds = oldCarIds.stream().collect(Collectors.toMap
                (SysDeptAuthRegion::getCode, Function.identity(), (en1, en2) -> en2)).values().stream().collect(Collectors.toList());

        newCarRegionIds.addAll(oldCarRegionIds);
        sysDeptAuthRegionService.saveBatch(newCarRegionIds);
    }
    @Override
    public void editDepartment(SysDepartment department) {
        // 先跟据数据信息获取
        SysDepartment de=this.baseMapper.selectById(department.getId());
        de.setTitle(department.getTitle());
        de.setSortOrder(department.getSortOrder());
        de.setStatus(department.getStatus());
        this.baseMapper.updateById(de);
        // 再查出来他自己的子集id 有哪些
        ArrayList<Long> region = new ArrayList<>();
        this.getRegionIds(region,department.getId());
        // 说明 这个集合下面有子集
        if(region.size()>0){
            List<Long> ids =new ArrayList<>();
            ids=region;
            ids.add(de.getId());
            // 对比丢失的数据
            if(department.getNewCarRegion().size()>0){
                // 说明新车还有数据
                List<SysDeptAuthRegion> newList=new ArrayList<>();
                BeanUtils.copyProperties(department.getNewCarRegion(), newList);
                // 查询现在的新车数据
                List<SysDeptAuthRegion> nList =sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query()
                        .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).eq(SysDeptAuthRegion::getDeptId, de.getId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()).notIn(SysDeptAuthRegion::getParentId,"0"));
                List<String> codes =getLose(nList,department.getNewCarRegion(),CarTypeEnum.newCar.toString());
                // 再看看这些code 下面还有没有子类的code
                if(codes.size()>0){
                    List<SysDeptAuthRegion> codeList =sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query()
                            .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).eq(SysDeptAuthRegion::getDeptId, de.getId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()).in(SysDeptAuthRegion::getParentId,codes));
                    if(codeList.size()>0){
                        for(SysDeptAuthRegion reg:codeList){
                            codes.add(reg.getCode());
                        }
                    }
                }
                // 清除丢失的数据
                if(codes.size()>0){
                    sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                            .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).in(SysDeptAuthRegion::getDeptId, ids).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()).in(SysDeptAuthRegion::getCode,codes));
                }

            }else {

                sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                        .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).in(SysDeptAuthRegion::getDeptId, ids).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));
            }
            if(department.getOldCarRegion().size()>0){
                // 说明二手车还有数据
                List<SysDeptAuthRegion> oldList=new ArrayList<>();
                BeanUtils.copyProperties(department.getOldCarRegion(), oldList);
                // 查询现在的二手车数据
                List<SysDeptAuthRegion> oList =sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query()
                        .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).eq(SysDeptAuthRegion::getDeptId, de.getId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()).notIn(SysDeptAuthRegion::getParentId,"0"));
                List<String> codes =getLose(oList,department.getOldCarRegion(),CarTypeEnum.oldCar.toString());
                // 再看看这些code 下面还有没有子类的code
                if(codes.size()>0){
                    List<SysDeptAuthRegion> codeList =sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query()
                            .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).eq(SysDeptAuthRegion::getDeptId, de.getId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()).in(SysDeptAuthRegion::getParentId,codes));
                    if(codeList.size()>0){
                        for(SysDeptAuthRegion reg:codeList){
                            codes.add(reg.getCode());
                        }
                    }
                }
                // 清除丢失的数据
                if(codes.size()>0){
                    sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                            .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).in(SysDeptAuthRegion::getDeptId, ids).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()).in(SysDeptAuthRegion::getCode,codes));
                }

            }else {
                sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                        .lambda().eq(SysDeptAuthRegion::getChannelId,DataAccessUtil.getChannelId()).in(SysDeptAuthRegion::getDeptId, ids).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
            }


        }
        // 第一步先去删除自己的数据
        sysDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query()
                .lambda().eq(SysDeptAuthRegion::getDeptId, de.getId()));
        // 再去判断  新车集合和二手车集合

        //新车展业区域
        ArrayList<SysDeptAuthRegion> newCarIds = Lists.newArrayList();
        for (SysDeptAuthRegion deptAuthRegion : department.getNewCarRegion()) {
            deptAuthRegion.setDeptId(department.getId());
            deptAuthRegion.setBusinessType(CarTypeEnum.newCar);
            deptAuthRegion.setIsChecked(deptAuthRegion.getChecked());
            deptAuthRegion.setChannelId(DataAccessUtil.getChannelId());
            newCarIds.add(deptAuthRegion);

            if (deptAuthRegion.getChecked()) {
                this.getRegionIds(newCarIds, deptAuthRegion.getCode(), department.getId(), DataAccessUtil.getChannelId(), CarTypeEnum.newCar,department.getParentId());
            }
        }
        if (newCarIds.size() > 0) {
            SysDeptAuthRegion gg = new SysDeptAuthRegion();
            gg.setCode("1");
            gg.setParentId("0");
            gg.setTitle("全国区域");
            gg.setIsParent(true);
            gg.setDeptId(department.getId());
            gg.setBusinessType(CarTypeEnum.newCar);
            gg.setIsChecked(true);
            gg.setChannelId(DataAccessUtil.getChannelId());
            newCarIds.add(gg);
        }


        List<SysDeptAuthRegion> newCarRegionIds = newCarIds.stream().collect(Collectors.toMap
                (SysDeptAuthRegion::getCode, Function.identity(), (en1, en2) -> en2)).values().stream().collect(Collectors.toList());

        //二手车展业区域
        ArrayList<SysDeptAuthRegion> oldCarIds = Lists.newArrayList();
        for (SysDeptAuthRegion deptAuthRegion : department.getOldCarRegion()) {
            deptAuthRegion.setDeptId(department.getId());
            deptAuthRegion.setBusinessType(CarTypeEnum.oldCar);
            deptAuthRegion.setIsChecked(deptAuthRegion.getChecked());
            deptAuthRegion.setChannelId(DataAccessUtil.getChannelId());
            oldCarIds.add(deptAuthRegion);

            if (deptAuthRegion.getChecked()) {
                this.getRegionIds(oldCarIds, deptAuthRegion.getCode(), department.getId(), DataAccessUtil.getChannelId(), CarTypeEnum.oldCar,department.getParentId());
            }
        }
        if (oldCarIds.size() > 0) {
            SysDeptAuthRegion ff = new SysDeptAuthRegion();
            ff.setCode("1");
            ff.setParentId("0");
            ff.setTitle("全国区域");
            ff.setIsParent(true);
            ff.setDeptId(department.getId());
            ff.setBusinessType(CarTypeEnum.oldCar);
            ff.setIsChecked(true);
            ff.setChannelId(DataAccessUtil.getChannelId());
            oldCarIds.add(ff);
        }
        List<SysDeptAuthRegion> oldCarRegionIds = oldCarIds.stream().collect(Collectors.toMap
                (SysDeptAuthRegion::getCode, Function.identity(), (en1, en2) -> en2)).values().stream().collect(Collectors.toList());

        newCarRegionIds.addAll(oldCarRegionIds);
        sysDeptAuthRegionService.saveBatch(newCarRegionIds);


    }

    // 递归查询 部门的子集
    private void getRegionIds(ArrayList<Long> region,  Long deptId) {
        //查询二级分类的对象
        List<SysDepartment> orgAuthorizeRegions = this.baseMapper.selectList(Wrappers.<SysDepartment>query()
                .lambda().eq(SysDepartment::getParentId, deptId));

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (SysDepartment orgAuthorizeRegion : orgAuthorizeRegions) {
            SysDepartment deptAuthRegion = new SysDepartment();
            BeanUtils.copyProperties(orgAuthorizeRegion, deptAuthRegion);
            region.add(deptAuthRegion.getId());

            //把二级分类的每一个ID，查询它下面的子节点
            this.getRegionIds(region, deptAuthRegion.getId());
        }
    }

    private static List<String> getLose(List<SysDeptAuthRegion> list1, List<SysDeptAuthRegion> list2,String type) {
        List<String> newList = new ArrayList<String>();
        // list1：原来的数据  list2:现在的数据

        // 第一步先把现在所有的数据放在集合里面
        Map<String, String> dataMap = new HashMap<String, String>();
        if (list2 != null && !list2.isEmpty()) {
            for (SysDeptAuthRegion id : list2) {
                if(type.equals(id.getBusinessType().toString())){
                    dataMap.put(id.getCode(), id.getCode());
                }
            }

            //  第二部 把原来的数据现在没有的，就把这个数据存储
            if (list1.size()>0){
                for (SysDeptAuthRegion id : list1) {
                    if (!dataMap.containsKey(id.getCode())) {
                        newList.add(id.getCode());
                    }
                }
            }
            return newList;
        } else {
            return newList;
        }
    }

    public void saveRegion(List<SysDeptAuthRegion> region, Long deptId, CarTypeEnum typeEnum, Long ffId) {
        // 声明一个存储新车的展业区域
        Set<SysDeptAuthRegion> newCarIds = new HashSet<>();
        for (SysDeptAuthRegion deptAuthRegion : region) {
            if (deptAuthRegion.getChecked()) {
                // 这个判断是不是全国。如果是全国直接把父级 的内容全给他
                if ("1".equals(deptAuthRegion.getCode())) {
                    List<SysDeptAuthRegion> all = sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>lambdaQuery().eq(SysDeptAuthRegion::getDeptId, ffId).eq(SysDeptAuthRegion::getBusinessType, typeEnum));
                    if (all.size() > 0) {
                        for (SysDeptAuthRegion aa : all) {
                            aa.setDeptId(deptId);
                        }
                        newCarIds.addAll(all);

                    }
                    SysDeptAuthRegion gg = deptAuthRegion;
                    gg.setCode("1");
                    gg.setParentId("0");
                    gg.setTitle("全国区域");
                    gg.setIsParent(true);
                    gg.setDeptId(deptId);
                    gg.setBusinessType(typeEnum);
                    gg.setIsChecked(deptAuthRegion.getChecked());
                    newCarIds.add(gg);
                    break;
                } else if (deptAuthRegion.getIsParent()) {
                    SysDeptAuthRegion gg = deptAuthRegion;
                    gg.setCode("1");
                    gg.setParentId("0");
                    gg.setTitle("全国区域");
                    gg.setIsParent(true);
                    gg.setDeptId(deptId);
                    gg.setBusinessType(typeEnum);
                    gg.setIsChecked(deptAuthRegion.getChecked());
                    newCarIds.add(gg);

                    // 进来就说明都是省级别的
                    // 我需要先把自己放给集合
                    deptAuthRegion.setDeptId(deptId);
                    deptAuthRegion.setBusinessType(typeEnum);
                    deptAuthRegion.setIsChecked(deptAuthRegion.getChecked());
                    deptAuthRegion.setChannelId(DataAccessUtil.getChannelId());
                    newCarIds.add(deptAuthRegion);
                    // 然后查询他所有的下级
                    List<SysDeptAuthRegion> all = sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>lambdaQuery().eq(SysDeptAuthRegion::getDeptId, ffId).eq(SysDeptAuthRegion::getBusinessType, typeEnum).eq(SysDeptAuthRegion::getParentId, deptAuthRegion.getCode()));
                    if (all.size() > 0) {
                        for (SysDeptAuthRegion aa : all) {
                            aa.setDeptId(deptId);
                        }
                        newCarIds.addAll(all);
                    }

                } else {

                    // 再把省的也给他
                    SysDeptAuthRegion p = sysDeptAuthRegionService.getOne(Wrappers.<SysDeptAuthRegion>lambdaQuery().eq(SysDeptAuthRegion::getDeptId, ffId).eq(SysDeptAuthRegion::getBusinessType, typeEnum).eq(SysDeptAuthRegion::getCode, deptAuthRegion.getParentId()));
                    p.setDeptId(deptId);
                    newCarIds.add(p);


                    // 这边给的应该是 市级
                    // 先给市的级别
                    deptAuthRegion.setDeptId(deptId);
                    deptAuthRegion.setBusinessType(typeEnum);
                    deptAuthRegion.setIsChecked(deptAuthRegion.getChecked());
                    deptAuthRegion.setChannelId(DataAccessUtil.getChannelId());
                    newCarIds.add(deptAuthRegion);


                    SysDeptAuthRegion gg = deptAuthRegion;
                    gg.setCode("1");
                    gg.setParentId("0");
                    gg.setTitle("全国区域");
                    gg.setIsParent(true);
                    gg.setDeptId(deptId);
                    gg.setBusinessType(typeEnum);
                    gg.setIsChecked(deptAuthRegion.getChecked());
                    newCarIds.add(gg);
                }
            }
        }
        List<SysDeptAuthRegion> newCarRegionIds = newCarIds.stream().collect(Collectors.toMap
                (SysDeptAuthRegion::getCode, Function.identity(), (en1, en2) -> en2)).values().stream().collect(Collectors.toList());
        sysDeptAuthRegionService.saveBatch(newCarRegionIds);
    }

    /**
     * 根据用户名获取同级、下级的部门id
     */
    public List<String> getDeptIds(String userLoginName) {

        ArrayList<Long> ids = Lists.newArrayList();
        //获取用户信息
        SysUser user = applyUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, userLoginName).eq(SysUser::getLockFlag, LockFlagEnum.NO.getValue()));
        SysDepartment dept = this.baseMapper.selectById(user.getDeptId());
        List<SysDepartment> listDept = this.baseMapper.selectList(Wrappers.<SysDepartment>query().lambda().eq(SysDepartment::getParentId, dept.getParentId()));
        listDept.forEach(en -> {
            ids.add(en.getId());
        });
        this.getDepartmentIds(ids, dept.getId());
        List<String> idsStr = ids.stream().map(str -> String.valueOf(str)).collect(Collectors.toList());

        return idsStr;
    }

    /**
     * 部门向下递归，包括自己
     *
     * @param userLoginName
     * @return
     */
    public List<Long> getDeptIdsDownAndSelf(String userLoginName) {

        SysUser user = applyUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, userLoginName));
        ArrayList<Long> ids = Lists.newArrayList();
        ids.add(user.getDeptId());
        this.getDepartmentIds(ids, user.getDeptId());
        return ids;
    }

    //部门递归方法(向下递归)
    public void getDepartmentIds(ArrayList<Long> ids, Long oneId) {
        //查询二级分类的对象
        List<SysDepartment> departments = list(Wrappers.<SysDepartment>query()
                .lambda().eq(SysDepartment::getParentId, oneId));

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (SysDepartment department : departments) {
            Long id = department.getId();
            ids.add(id);
            //把二级分类的每一个ID，查询它下面的子节点
            this.getDepartmentIds(ids, id);
        }
    }


    //部门递归方法(向上递归)
    private void getDepartmentUp(ArrayList<SysDepartment> list, Long oneId) {
        //查询二级分类的对象
        SysDepartment department = getOne(Wrappers.<SysDepartment>query()
                .lambda().eq(SysDepartment::getId, oneId));
        if (ObjectUtils.isNotEmpty(department)) {
            list.add(department);
            this.getDepartmentUp(list, department.getParentId());
        }
    }

    //展业区域递归方法
    private void getRegionIds(ArrayList<SysDeptAuthRegion> region, String oneId, Long deptId, Long channelId, CarTypeEnum typeEnum,Long parentId) {
        //查询二级分类的对象
        List<SysDeptAuthRegion> orgAuthorizeRegions = sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query()
                .lambda().eq(SysDeptAuthRegion::getParentId, oneId).eq(SysDeptAuthRegion::getChannelId, channelId).eq(SysDeptAuthRegion::getBusinessType, typeEnum).eq(SysDeptAuthRegion::getDeptId,parentId));

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (SysDeptAuthRegion orgAuthorizeRegion : orgAuthorizeRegions) {

            SysDeptAuthRegion deptAuthRegion = new SysDeptAuthRegion();
            BeanUtils.copyProperties(orgAuthorizeRegion, deptAuthRegion);
            deptAuthRegion.setDeptId(deptId);
            deptAuthRegion.setBusinessType(typeEnum);
            deptAuthRegion.setChannelId(channelId);
            deptAuthRegion.setIsChecked(true);
            region.add(deptAuthRegion);

            //把二级分类的每一个ID，查询它下面的子节点
            this.getRegionIds(region, deptAuthRegion.getCode(), deptId, channelId, typeEnum,parentId);
        }
    }

    //展业区域递归方法
    private void getAddRegionIds(ArrayList<SysDeptAuthRegion> region, String oneId, Long deptId, Long channelId, CarTypeEnum typeEnum,Long parentId) {
        //查询二级分类的对象
        List<SysDeptAuthRegion> orgAuthorizeRegions = sysDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query()
                .lambda().eq(SysDeptAuthRegion::getParentId, oneId).eq(SysDeptAuthRegion::getChannelId, channelId).eq(SysDeptAuthRegion::getBusinessType, typeEnum).eq(SysDeptAuthRegion::getDeptId,parentId));

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (SysDeptAuthRegion orgAuthorizeRegion : orgAuthorizeRegions) {

            SysDeptAuthRegion deptAuthRegion = new SysDeptAuthRegion();
            BeanUtils.copyProperties(orgAuthorizeRegion, deptAuthRegion);
            deptAuthRegion.setDeptId(deptId);
            deptAuthRegion.setBusinessType(typeEnum);
            deptAuthRegion.setChannelId(channelId);
            deptAuthRegion.setIsChecked(true);
            region.add(deptAuthRegion);

            //把二级分类的每一个ID，查询它下面的子节点
            this.getAddRegionIds(region, deptAuthRegion.getCode(), deptId, channelId, typeEnum,parentId);
        }
    }

}
